<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"  @submit="handleInitTable">

      <t-col :span="3">
        <t-form-item label="套餐名" name="name">
           <t-input v-model:value="params.name" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="状态" name="status">
          <t-select
            v-model:value="params.status"
            :options="dictionaryStore.get('common_status')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="tenantPackageListCRUD.page"
      column-controller-key="SystemTenantPackage"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button
            v-permission="['system:tenant-package:create']"
            @click="handleOpenDialog('create', { 
              status: 0
              })"
          >
            新建套餐
          </t-button>
        </div>
      </template>
   

      <template #status="{ row }">
        <t-tag theme="primary" variant="light">
          {{ dictionaryStore.analysis('common_status', row.status) }}
        </t-tag>
      </template>

      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      
      <template #operation="{ row }">
        <t-space break-line>
          <t-link
            v-permission="['system:tenant-package:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['system:tenant-package:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['system:tenant-package:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly, mode }"
      :api-map="tenantPackageListCRUD"
      header="*套餐"
      :on-before-set-data="handleDialogSetData"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="套餐名" name="name" :rules="[{ required: true, message: '请输入套餐名' }]">
        <t-input v-model:value="formData.name" placeholder="请输入套餐名" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="菜单权限" name="menuIds">
      <div>
        <t-space style="margin: 6px">
          是否全选<t-switch @change="handleChangeMenuChecked" /> 是否展开<t-switch @change="handleChangeMenuExpanded" />
        </t-space>
        <t-tree
          ref="menuTreeRef"
          v-model:value="formData.menuIds"
          :data="simpleMenuTree"
          :keys="{ value: 'id', label: 'name' }"
          checkable
          check-strictly
          @change="handleMenuIdsChange"
        />
      </div>
    </t-form-item>
 
  
  
      <t-form-item label="状态" name="status" :rules="[{ required: true, message: '请选择租户状态' }]">
        <t-switch v-model:value="formData.status" :custom-value="[0, 1]" :disabled="readonly" />
      </t-form-item>
      <t-form-item  label="备注" name="remark" >
        <t-input v-model:value="formData.remark" placeholder="请输入备注" clearable :readonly="readonly" />
      </t-form-item>


    </custom-dialog>
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'SystemTenantPackage',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, SwitchValue, TableCol } from 'tdesign-vue-next';
import { onMounted, onUpdated, ref, useTemplateRef } from 'vue';

import { tenantPackageListCRUD } from '@/api/tenant/package';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import listToTree from '@/utils/listToTree';
import { getSimpleMenuList } from '@/api/system/menu';
import { useDictionaryStore } from '@/store';


// 字典仓库
const dictionaryStore = useDictionaryStore();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'name', title: '套餐名', width: 100 },
  { colKey: 'status', title: '状态', width: 180 },
  { colKey: 'remark', title: '备注', width: 180 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 160, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
// 精简菜单树
const simpleMenuTree = ref([]);
// 处理获取精简菜单树
const handleGetSimpleMenuTree = () => {
  getSimpleMenuList().then((data) => {
    data.forEach((item: Record<string, any>) => {
      if (item.type === 3) item.name = `【权限】${item.name}`;
    });
    simpleMenuTree.value = listToTree(data);
  });
};
// 处理改变菜单选中
const handleChangeMenuChecked = (value: SwitchValue) => {
  if (isOperationMenu.value) return;
  isOperationMenu.value = true;
  const items = menuTreeRef.value.getItems();
  items.forEach((item) => {
    menuTreeRef.value.setItem(item.value, { checked: value as boolean });
  });
  isOperationMenu.value = false;
};
// 处理改变菜单展开
const handleChangeMenuExpanded = (value: SwitchValue) => {
  if (isOperationMenu.value) return;
  isOperationMenu.value = true;
  const items = menuTreeRef.value.getItems();
  items.forEach((item) => {
    menuTreeRef.value.setItem(item.value, { expanded: value as boolean });
  });
  isOperationMenu.value = false;
};
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable()
})
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  handleGetSimpleMenuTree();
  customDialogRef.value.open(mode, params);
};
// 处理对话框设置数据
const handleDialogSetData = (params: Record<string, any>) => {

};
// 菜单树ref
const menuTreeRef = useTemplateRef('menuTreeRef');
// 是否操作菜单
const isOperationMenu = ref(false);
// 处理菜单id改变
const handleMenuIdsChange = (_: any, { node }: any) => {
  if (isOperationMenu.value) return;
  isOperationMenu.value = true;
  const parents = menuTreeRef.value.getParents(node.value);
  parents.forEach((item) => {
    if (!item.checked) {
      menuTreeRef.value.setItem(item.value, { checked: true });
    }
  });
  const items = menuTreeRef.value.getItems(node.value);
  items.forEach((item) => {
    menuTreeRef.value.setItem(item.value, { checked: node.checked });
  });
  isOperationMenu.value = false;
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  tenantPackageListCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

</script>

<style lang="less" scoped></style>
